package server;
import common.*;

import java.net.*;
import java.util.*;
import java.io.*;

public class ServerMain 
{
	// TODO: this should be a list of Client objects
	public static List<ClientAccount> connectedClients = Collections.synchronizedList(new ArrayList<ClientAccount>());
	
	public static int findConnectedClient(String username)
	{
		synchronized(ServerMain.connectedClients)
		{
			for(int i=0; i<ServerMain.connectedClients.size(); ++i)
				if(ServerMain.connectedClients.get(i).username.equals(username))
					return i;
		}
		
		return -1;			
	}
	
	public static void main(String[] args) 
	{
		ServerSocket socket = null;
		
		// Initialize paths 
		Utils.AppFolder = System.getProperty("user.dir");
		if(!Utils.AppFolder.endsWith("/"))
			Utils.AppFolder += "/";
		
		Utils.ContactsFolder = Utils.AppFolder+"Contacts";
			
		System.out.println("Application Folder: "+Utils.AppFolder);
		System.out.println("Contacts Folder: "+Utils.ContactsFolder);
		
		// make sure the contacts dir is created
		if (!new File(Utils.ContactsFolder).exists())
			new File(Utils.ContactsFolder).mkdir();
		
		Utils.ContactsFolder += "/";
		
		// Start the server socket
		try
		{
			socket = new ServerSocket(Constants.SERVER_PORT);
		} // TRY
		catch(Exception e)
		{
			System.out.println("While instantiating a server socket:");
			e.printStackTrace();
			System.exit(-1);
		}
		
		System.out.println("Server socket running on port "+Constants.SERVER_PORT+"...");
		
		// Keep looping waiting for connections
		while(true)
		{
			try
			{
				Socket clientSocket = socket.accept();
				System.out.println("Client connected from "+clientSocket.getRemoteSocketAddress().toString());								
				
				// start a new thread for that connection
				ClientThread thread = new ClientThread();
				thread.clientSocket = SocketWrapper.dup(clientSocket);
				new Thread(thread).start();								
			} // TRY
			catch(SocketTimeoutException e)
			{
				// do nothing, we can loop again and listen for further connections
			}
			catch(Exception e)
			{
				// All other exceptions are deadly
				System.out.println("While waiting for new connections:");
				e.printStackTrace();
				System.exit(-1);
			} // CATCH
		} // WHILE
	}

}
